// active/publish/publish.js
import api from '../../utils/api.js';
import network from '../../utils/network.js';
import utils from '../../utils/utils.js';
import notice from '../../utils/notice.js';
import location from '../../utils/location.js';
import formatDate from '../../utils/format_date.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        count: 0,
        cover: '',
        processType: 1,
        siteName: '',
        city: '',
        poi: '',
        address: '',
        lat: 0,
        lng: 0,
        timerList: [],
        calendarShow: false,
        timerValue: {
            list: []
        },
        originFiles: [],
        fileList: [],
        gridConfig: {
            column: 3,
            width: 190,
            height: 190,
        },
        config: {
            count: 1,
        },
        max: 9,
        mode: 2,
        isGroup: 1,
        groupCode: '',
        link: '',
        startTimeVisible: false,
        startTime: '',
        endTimeVisible: false,
        poiVisible: false,
        poiList: [
          {
            cover: 'http://devhui.salonhui.com/assets/cover1.png',
            title: '龙湖清能天奕loft1栋-1101',
            local: '武汉 · 龙湖滨江天街'
          },
          {
            cover: 'http://devhui.salonhui.com/assets/cover1.png',
            title: '龙湖清能天奕loft1栋-1101',
            local: '武汉 · 龙湖滨江天街'
          },
          {
            cover: 'http://devhui.salonhui.com/assets/cover1.png',
            title: '龙湖清能天奕loft1栋-1101',
            local: '武汉 · 龙湖滨江天街'
          },
          {
            cover: 'http://devhui.salonhui.com/assets/cover2.png',
            title: '龙湖清能天奕loft1栋-1101',
            local: '武汉 · 龙湖滨江天街'
          },
          {
            cover: 'http://devhui.salonhui.com/assets/cover1.png',
            title: '龙湖清能天奕loft1栋-1101',
            local: '武汉 · 龙湖滨江天街'
          }
        ],
        endTime: '',
        offlineAmount: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.siteId) {
            this.siteId = options.siteId;
            this.setData({
                timerValue: {
                    list: [],
                    siteId: this.siteId
                }
            })
        }
        if (options.couponType) {
            this.couponType = options.couponType;
        }
        if (options.accommodate) {
            this.accommodate = options.accommodate;
        }
        if (options.name) {
            this.setData({
                siteName: options.name
            })
        }
        // if (options.active) {
        //     let active = JSON.parse(decodeURIComponent(options.active));
        //     console.log(active)
        //     this.setData({
        //         timerValue: {
        //             list: active.bookingTimes,
        //             siteId: active.siteId
        //         },
        //         // siteName: options.name,
        //         cover: '',
        //         processType: 1,
        //     })
        //     this.couponId = options.couponId;
        //     this.accommodate = options.accommodate;
        // }

        let time = formatDate.formatTime(new Date(), 'yyyy-MM-dd HH:mm');
        this.setData({
            startTime: time,
            endTime: time
        })

        notice.addNotice("SelectCoupon", this.selectCoupon, this);
        notice.addNotice("ActivePublish", this.selectCoupon, this);
    },

    selectCoupon(e) {
        this.siteId = e.siteId;
        this.couponType = e.couponType;
        this.accommodate = e.accommodate;
        this.setData({
            siteName: e.name,
            timerValue: {
                list: [],
                siteId: this.siteId
            }
        })
    },
    choosePoi () {
      this.setData({
        poiVisible: true
      })
    },
    closePoi () {
      this.setData({
        poiVisible: false
      })
    },
    preventTouchMove () {},
    chooseAddress() {
        // wx.getLocation({
        //     type: 'wgs84',
        //     success: res => {
        //         wx.chooseLocation({
        //             latitude: res.latitude,
        //             longitude: res.longitude,
        //             success: data => {
        //                 console.log(data)
        //             }
        //         })
        //     }
        // })

        wx.chooseLocation({
            success: data => {
                console.log(data)
                if (data.name) {
                    this.setData({
                        poi: data.name,
                        address: data.address,
                        lat: data.latitude,
                        lng: data.longitude
                    })
                    location.reverseGeocoder(data.latitude, data.longitude).then(res => {
                        console.log(res)
                        this.setData({
                            city: res.city
                        })
                    });
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '请选择活动地点'
                    })
                }
            }
        })
    },

    onUnload() {
        notice.removeNotice("SelectCoupon", this);
        notice.removeNotice("ActivePublish", this);
    },
    selectedTypeTap(e) {
        let type = Number(e.currentTarget.dataset.type);
        this.setData({
            processType: type
        })
    },

    goSite(e) {
        wx.navigateTo({
            url: '/site/site/site?idx=' + e.currentTarget.dataset.idx
        })
        // wx.chooseLocation({
        //     success (res) {
        //       console.log(res)
        //     }
        //   })
    },

    inputName(e) {
        this.name = e.detail.value;
        this.setData({
            count: e.detail.cursor
        })
    },

    updateCover() {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: res => {
                console.log(res.tempFiles[0].tempFilePath)
                network.uploadFile(res.tempFiles[0].tempFilePath, 'file', {}).then(img => {
                    console.log(img)
                    // this.setData({
                    //     cover: img
                    // })
                })
            }
        })
    },

    inputCount(e) {
        this.peopleNum = e.detail.value;
    },

    codeInput(e) {
        this.code = e.detail.value;
    },

    startTimeTap() {
        this.setData({
            startTimeVisible: true
        })
    },

    endTimeTap() {
        this.setData({
            endTimeVisible: true
        })
    },

    onStartConfirm(e) {
        this.setData({
            startTimeVisible: false,
            startTime: e.detail.value
        })
    },

    onEndConfirm(e) {
        this.setData({
            endTimeVisible: false,
            endTime: e.detail.value
        })
    },

    handleChange(e) {
        this.setData({
            checked: e.detail.checked,
            mode: e.detail.value == 0 ? 1 : 2
        });
    },

    linkChange(e) {
        this.setData({
            isGroup: e.detail.value == 0 ? 1 : 2
        });
    },

    inputLink(e) {
        this.setData({
            line: e.detail.value
        })
    },

    inputAmount2(e) {
        this.setData({
            offlineAmount: e.detail.value
        })
    },

    selectedTimerTap() {
        // network.getJson(api.getSite, {
        //     id: this.site
        // }).then(res => {
        //     let timerAmount = [res.data.amFees, res.data.pmFees, res.data.atFees];
        //     this.setData({
        //         details: res.data,
        //         timerValue: {
        //             timerAmount,
        //             list: [],
        //             siteId: res.data.id
        //         }
        //     })
        // })
        // if (!this.siteId) {
        //     wx.showToast({
        //         icon: 'none',
        //         title: '请选择场地'
        //     })
        //     return;
        // }
        this.setData({
            calendarShow: true
        })
    },

    submitCalendar(e) {
        this.setData({
            timerList: e.detail
        })
    },

    inputAmount(e) {
        this.data.timerList[e.currentTarget.dataset.index].amount = e.detail.value;
        this.setData({
            timerList: this.data.timerList
        })
    },

    detailInput(e) {
        this.detail = e.detail.value;
    },

    handleSuccess(e) {
        const {
            files
        } = e.detail;
        this.setData({
            originFiles: files,
        });
    },
    handleRemove(e) {
        const {
            index
        } = e.detail;
        const {
            originFiles
        } = this.data;
        originFiles.splice(index, 1);
        this.setData({
            originFiles,
        });
    },
    handleClick(e) {
        console.log(e.detail.file);
    },

    handleAdd(e) {
        const {
            files
        } = e.detail;

        files.forEach(file => this.onUpload(file))
    },
    onUpload(file) {
        const {
            fileList
        } = this.data;

        this.setData({
            fileList: [...fileList, {
                ...file,
                status: 'loading'
            }],
        });
        const {
            length
        } = fileList;

        network.uploadFile(file.url, 'file', {}).then(img => {
            this.setData({
                [`fileList[${length}]`]: {
                    file: img,
                    status: 'done'
                }
            });
        })
    },

    updateGroupCode() {
        let that = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album'],
            success(res) {
                let url = res.tempFiles[0].tempFilePath;
                network.uploadFile(url, 'file', {}).then(img => {
                    that.setData({
                        groupCode: img
                    });
                })
            }
        })
    },

    publishTap() {
        utils.fromEvent().then(() => {
            if (!this.data.cover) {
                wx.showToast({
                    icon: 'none',
                    title: '请上传活动封面',
                })
                return;
            }
            if (!this.name) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入活动主题',
                })
                return;
            }
            if (this.data.fileList.length == 0) {
                wx.showToast({
                    icon: 'none',
                    title: '请上传活动海报',
                })
                return;
            }
            // if (!this.peopleNum) {
            //     wx.showToast({
            //         icon: 'none',
            //         title: '请输入报名人数',
            //     })
            //     return;
            // }

            // if (Number(this.peopleNum) > Number(this.accommodate)) {
            //     wx.showToast({
            //         icon: 'none',
            //         title: `最多容纳${this.accommodate}人`,
            //     })
            //     return;
            // }
            // if (this.data.mode == 1) {
            //     if (!this.code) {
            //         wx.showToast({
            //             icon: 'none',
            //             title: '请输入邀请码',
            //         })
            //         return;
            //     }
            // }
            if (this.data.processType == 1) {
                if (!this.data.poi.length) {
                    wx.showToast({
                        icon: 'none',
                        title: '请选择活动地点',
                    })
                    return;
                }
                if (this.data.timerList.length <= 0) {
                    wx.showToast({
                        icon: 'none',
                        title: '请选择活动时间',
                    })
                    return;
                }
                for (let i = 0; i < this.data.timerList.length; i++) {
                    delete this.data.timerList[i].id;
                    this.data.timerList[i].timer = this.data.timerList[i].mode;
                }
            } else {
                if (this.data.startTime == this.data.endTime) {
                    wx.showToast({
                        icon: 'none',
                        title: '开始时间不能与结束时间相同',
                    })
                    return;
                }
                if (this.data.isGroup == 1) {
                    if (!this.data.groupCode) {
                        wx.showToast({
                            icon: 'none',
                            title: '请上传微信群二维码',
                        })
                        return;
                    }
                } else {
                    if (!this.data.link) {
                        wx.showToast({
                            icon: 'none',
                            title: '活动链接不能为空',
                        })
                        return;
                    }
                }
            }
            let images = [];
            for (let i = 0; i < this.data.fileList.length; i++) {
                images.push(this.data.fileList[i].file);
            }

            let user = getApp().globalData.userInfo;
            let param = {
                creator: user.id,
                updater: user.id,
                cover: this.data.cover,
                name: this.name,
                // peopleNum: this.peopleNum,
                mode: this.data.mode, // '活动性质，1=私人活动，2=公开活动'
                images: images.join(','),
                details: this.detail,
                processType: this.data.processType
            }

            if (param.processType == 1) {
                param.city = this.data.city;
                param.poi = this.data.poi;
                param.address = this.data.address;
                param.lat = this.data.lat;
                param.lng = this.data.lng;
                param.bookingTimes = this.data.timerList;
            } else {
                let timer = {};
                if (new Date(this.data.startTime).getTime() > new Date(this.data.endTime).getTime()) {
                    timer.startTime = this.data.endTime + ':00';
                    timer.endTime = this.data.startTime + ':00';
                } else {
                    timer.startTime = this.data.startTime + ':00';
                    timer.endTime = this.data.endTime + ':00';
                }
                timer.amount = this.data.offlineAmount;
                param.link = this.data.link;
                param.groupCode = this.data.groupCode;
                param.bookingTimes = [timer];
            }

            network.postJson(api.createActive, param).then(res => {
                notice.postNotice("RefreshOrder");
                wx.showToast({
                    icon: 'none',
                    title: '发布成功'
                })
                setTimeout(function () {
                    wx.reLaunch({
                        url: '/home/success/success?mode=PUBLISH&activeId=' + res.data + '&activeName=' + encodeURIComponent(this.name) + '&activeImage=' + encodeURIComponent(this.data.cover)
                    })
                }, 2000)
            })
        })
    }
})